//
//  RHPlantInfoViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/24.
//

#import "RHPlantInfoViewController.h"
#import "RHPlantInfoCell.h"
#import "RHPlantTopoCell.h"
#import "RHPlantInfoChartCell.h"
#import "RHDeviceListViewController.h"
#import "RHPlantDetailModel.h"
#import "RHDeviceStatusVC.h"
#import "RHDeviceBindVC.h"
#import "DevChartParamsModel.h"
#import "DevChartModel.h"
#import "SYChartTool.h"
#import "WSDatePickerView.h"
#import "RHEnergyStatisticsFullChartVC.h"
#import "DeviceChartFieldModel.h"
#import "IFMMenu.h"
#import "RHEditPlantVC.h"
#import "RHPlantTransferVC.h"
#import "RHEnergyStatisticsCell.h"
#import "RHPlantDeviceCell.h"
#import "RHEnergySaveCell.h"
#import "RHDeviceModel.h"
#import "RHDeviceStatusVC.h"
#import "RHPlantInfoTopoFullScreenVC.h"
#import <MGSwipeTableCell.h>
#import "KWTMGRNSettingVC.h"
#import "RHEndPointTypeModel.h"
#import "RHEndPointModel.h"
#import "KWTPlantMasterDeviceListVC.h"
#import "KWT233KInvSettingVC.h"
#import "RHTools.h"
#import "RHSolarkSettingVC.h"
#import "RHHiSolarSettingVC.h"

@interface RHPlantInfoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,assign) __block NSInteger selectIndex;

@property (nonatomic, strong) RHPlantDetailModel *detailModel;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

@property (nonatomic ,strong) NSArray *titleArr;

@property (nonatomic, strong) NSArray *deviceArr;

@property (nonatomic, assign) NSInteger deviceCount;

//节能减排
@property (nonatomic ,strong) NSDictionary *emissionReductionDic;

@property (nonatomic ,strong) IFMMenu *menu;
@end

@implementation RHPlantInfoViewController
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.menu dismissMenu];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = self.plantModel.plantName;
    _selectIndex = 0;
    [self createData];
    [self setupUI];
    [self getData];
}

-(void)createData
{
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"PlantEnergyStatistics"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
}

-(void)getData
{
    [self getStationDetail];
    [self getDeviceOfPlant];
    [self getEnergyStatisticsWithChartModel:[self.chartParamsModel.chartList firstObject
                                          ]];
    [self getEmissionReduction];
}

#pragma mark ----- 节能减排(社会贡献)

-(void)getEmissionReduction
{
    [BaseModel startGetWithCompletionAPIKey:H_getEmissionReduction argument:@{@"plantId":@(self.plantModel.plant_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        self.emissionReductionDic = request.responseJSONObject[@"data"];
        [self.tableView reloadData];
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

#pragma mark ----- 获取电站详情


//电站信息,还有光伏,馈网,电池,负载等数据
-(void)getStationDetail
{
    [RHPlantDetailModel startGetWithCompletionAPIKey:H_getStationDetail argument:@{@"plantId":@(self.plantModel.plant_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.detailModel = resultModel.data;
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

//获取电站下设备
#pragma mark ---- 获取电站下的设备 -------
-(void)getDeviceOfPlant
{

    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id),
                           @"pageNum":@(1),
                           @"pageSize":@(5)
    };
    [QMUITips showLoadingInView:self.view];
    [RHDeviceModel startGetWithCompletionAPIKey:H_getPlantDeviceListByStatus argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.deviceCount = [request.responseObject[@"total"] integerValue];
            self.deviceArr = resultModel.data;
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        [self.tableView endFooterRefresh];
    }];
}

#pragma mark ----- 能量统计
-(void)getEnergyStatisticsWithChartModel:(DevChartModel*)chartModel
{
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id),@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    [BaseModel startWithCompletionAPIKey:H_getRegularStatisticsByPlant argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        chartModel.allDataArray = request.responseJSONObject[@"data"];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}


-(void)changeDate{
    DevChartModel *chartModel = [self.chartParamsModel.chartList firstObject];
    //NSString *dateFormatStr = @"yyyy-MM-dd HH:mm";
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYearMonthDay;
    }
    kWeakSelf;
    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        [self getEnergyStatisticsWithChartModel:chartModel];
//        if (chartModel.timeType == TimeType_Day) {
//            [self getEnergyStatisticsWithChartModel:chartModel];
//        }else if (chartModel.timeType == TimeType_Month){
//            [self getYearOrMonth:YES model:chartModel];
//            [self.tableView reloadData];
//        }else if (chartModel.timeType == TimeType_Year){
//            [self getYearOrMonth:NO model:chartModel];
//            [self.tableView reloadData];
//        }
        
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}



- (void)setupUI{
    kWeakSelf;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getDeviceOfPlant) name:DeviceListNeedUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPlantInfo) name:PlantInfoDidChangeNotification object:nil];
    self.titleArr = @[@"",@"",@"能量统计".rh_localized,@"我的设备".rh_localized,@"社会贡献".rh_localized];
    
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem qmui_itemWithImage:[[UIImage imageNamed:@"kwt_plant_more"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] target:self action:@selector(rightBarButtonDown)];
    }
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHPlantInfoCell class] forCellReuseIdentifier:@"RHPlantInfoCell"];
    [_tableView registerClass:[RHPlantTopoCell class] forCellReuseIdentifier:PETopoHEBatCell];
    [_tableView registerClass:[RHPlantTopoCell class] forCellReuseIdentifier:PETopoMECell];
    [_tableView registerClass:[RHEnergyStatisticsCell class] forCellReuseIdentifier:@"RHEnergyStatisticsCell"];
    [_tableView registerClass:[RHPlantDeviceCell class] forCellReuseIdentifier:@"OneDeviceCell"];
    [_tableView registerClass:[RHPlantDeviceCell class] forCellReuseIdentifier:@"NoDeviceCell"];
    [_tableView registerClass:[RHPlantDeviceCell class] forCellReuseIdentifier:@"MoreDeviceCell"];
    [_tableView registerClass:[RHEnergySaveCell class] forCellReuseIdentifier:@"RHEnergySaveCell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getData];
    }];
}

//导航栏弹出
- (void)rightBarButtonDown
{
    kWeakSelf;
   NSMutableArray *menuItems = [[NSMutableArray alloc] initWithObjects:
                  
                  [IFMMenuItem itemWithImage:[UIImage imageNamed:@"plant_edit"]
                                       title:@"编辑".rh_localized
                                      action:^(IFMMenuItem *item) {
                        [weakSelf editPlant];
                    }],
                  [IFMMenuItem itemWithImage:[UIImage imageNamed:@"plant_transfer"]
                                       title:@"转让".rh_localized
                                      action:^(IFMMenuItem *item) {
                        [weakSelf transforPlant];
                   }],
                  [IFMMenuItem itemWithImage:[UIImage imageNamed:@"plant_add_device"]
                                       title:@"添加设备".rh_localized
                                      action:^(IFMMenuItem *item) {
                        [weakSelf addDeviceToPlant];
                       
       
                  }],
                    [IFMMenuItem itemWithImage:[UIImage imageNamed:@"plant_chg_config"]
                                         title:@"充放电配置".rh_localized
                                        action:^(IFMMenuItem *item) {
                          [weakSelf getPlantMasterDevice];
                         
         
                    }],nil];
    IFMMenu *menu = [[IFMMenu alloc] initWithItems:menuItems];
    menu.menuCornerRadiu = 8;
    menu.showShadow = YES;
    menu.minMenuItemHeight = 45;
    menu.titleColor = [UIColor colorWithHexString:@"3F4443" alpha:0.6];
    menu.titleFont = [UIFont systemFontOfSize:15];
    menu.menuBackgroundStyle = IFMMenuBackgroundStyleLight;
    [menu showFromNavigationController:self.navigationController WithX:[UIScreen mainScreen].bounds.size.width-32];
    self.menu = menu;
}


#pragma mark ------ 编辑电站
-(void)editPlant{
    RHEditPlantVC *editVC = [[RHEditPlantVC alloc]init];
    editVC.plantModel = self.plantModel.yy_modelCopy;
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark ------ 转让电站
-(void)transforPlant{
    RHPlantTransferVC *vc = [[RHPlantTransferVC alloc]init];
    vc.plantId = self.plantModel.plant_id;
    kWeakSelf;
    vc.transferBlock = ^{
        [weakSelf.navigationController popViewControllerAnimated:NO];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------ 添加设备
-(void)addDeviceToPlant
{
    RHDeviceBindVC *bindDeviceVC = [[RHDeviceBindVC alloc]init];
    bindDeviceVC.plantModel = self.plantModel;
    [self.navigationController pushViewController:bindDeviceVC animated:YES];
}

#pragma mark ------1. 充放电配置  获取电站下的主设备
-(void)getPlantMasterDevice
{
    [QMUITips showLoadingInView:self.view];
    [RHDeviceModel startGetWithCompletionAPIKey:H_getMasterDeviceIds argument:@{@"plantId":@(self.plantModel.plant_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            
//            KWTPlantMasterDeviceListVC *masterDevListVC = [[KWTPlantMasterDeviceListVC alloc]init];
//            masterDevListVC.deviceArr = self.deviceArr;
//            [self.navigationController pushViewController:masterDevListVC animated:YES];
//            return;
            //一个设备直接进配置页面
            NSArray *arr = resultModel.data;
            if (arr.count == 1) {
                RHDeviceModel *device = arr.firstObject;
                [self getEndPointReration:device];
            }else if(arr.count>1){
                //进设备列表
                KWTPlantMasterDeviceListVC *masterDevListVC = [[KWTPlantMasterDeviceListVC alloc]init];
                masterDevListVC.deviceArr = arr;
                [self.navigationController pushViewController:masterDevListVC animated:YES];
            }else{
                //没有设备
                [QMUITips showInfo:@"当前电站下无可配置的设备".rh_localized];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
      
}

#pragma mark -----1. 获取设备端点关系 -------
- (void)getEndPointReration:(RHDeviceModel*)device{
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%@",H_getDevRelationTypeList,SafeStr(device.deviceId)];
    [RHEndPointTypeModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
        
            NSArray *typeArr = resultModel.data;
            
            __block BOOL canConfig = NO;
            [typeArr enumerateObjectsUsingBlock:^(RHEndPointTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSArray *allInvType = [RHTools allConfigedInverterType];
                if ([allInvType containsObject:obj.endpoint]&&obj.nodes.count>0) {
                    RHEndPointModel *endpointModel = [obj.nodes firstObject];
                    if ([endpointModel.endpoint isEqualToString:InvType_InvMegarevoLv12KW]) {
                        canConfig = YES;
                        *stop = YES;
                        KWTMGRNSettingVC *settingVC = [[KWTMGRNSettingVC alloc]initWithDeviceModel:device endpoint:endpointModel];
                        [self.navigationController pushViewController:settingVC animated:YES];
                        
                    }else if([endpointModel.endpoint isEqualToString:InvType_PCS_BCS_B_HM_USX2]){
                        canConfig = YES;
                        *stop = YES;
                        KWT233KInvSettingVC *settingVC = [[KWT233KInvSettingVC alloc]initWithDeviceModel:device endpoint:endpointModel];
                        [self.navigationController pushViewController:settingVC animated:YES];
                        
                    }else if ([endpointModel.endpoint isEqualToString:InvType_Sol_Ark_30K_3P_208V]||
                        [endpointModel.endpoint isEqualToString:InvType_Sol_Ark_60K_3P_480V]) {//61度电 Solark
                        canConfig = YES;
                        *stop = YES;
                        RHSolarkSettingVC *solisVC = [[RHSolarkSettingVC alloc]initWithDeviceModel:device endpoint:endpointModel];
                        [self.navigationController pushViewController:solisVC animated:YES];
                        
                    }else if([endpointModel.endpoint isEqualToString:InvType_InvHISOLAR15KW]){//海索
                        canConfig = YES;
                        *stop = YES;
                        RHHiSolarSettingVC *hiSolarVC = [[RHHiSolarSettingVC alloc]initWithDeviceModel:device endpoint:endpointModel];
                        [self.navigationController pushViewController:hiSolarVC animated:YES];
                        
                    }
                }
                
            }];
            if (canConfig == NO) {
                [QMUITips showInfo:@"当前电站下无可配置的设备".rh_localized];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
    
    
}

#pragma mark ------- 2.获取逆变器类型 ---------
-(void)getIverterType:(RHEndPointTypeModel*)endPointTypeModel device:(RHDeviceModel *)device
{
    if (endPointTypeModel.nodes.count==0) {
        return;
    }
    RHEndPointModel *endpointModel = [endPointTypeModel.nodes firstObject];
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getParamStatusData argument:@{@"deviceId":ValidNullData(device.deviceId),@"sn":ValidNullData(endpointModel.sn)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            device.inverterType = (DevInverterType)[request.responseJSONObject[@"data"][@"Inv_DevType"] integerValue];
             if(device.inverterType == DevInverterTypeMGRN7K||
                device.inverterType == DevInverterTypeMGRN12K){
                 KWTMGRNSettingVC *settingVC = [[KWTMGRNSettingVC alloc]initWithDeviceModel:device endpoint:endpointModel];
                 
                 [self.navigationController pushViewController:settingVC animated:YES];
             }else{
                 [QMUITips showInfo:@"当前电站下无可配置的设备".rh_localized];
             }

        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
        
    }];
}

#pragma mark ------ 获取电站信息
-(void)getPlantInfo
{
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_plantDetail,self.plantModel.plant_id];
    [RHPlantModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.plantModel = resultModel.data;
            self.navigationItem.title = self.plantModel.plantName;
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)deleteDeviceFromPlantWithDev:(RHDeviceModel*)devModel
{
    [QMUITips showLoading:@"" inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_removePlantDevice argument:@{@"deviceId":devModel.deviceId,@"plantId":@(self.plantModel.plant_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized];
           
            [self getDeviceOfPlant];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    UIView *headView = kView;
//    headView.backgroundColor = CFTabViewBgColor;
//    UILabel *titleLab = [[QMUILabel alloc]init];
//    titleLab.font = kBOLDSYSTEMFONT(16);
//    titleLab.textColor = kColorRGB(0, 0, 0);
//    titleLab.textAlignment = NSTextAlignmentLeft;
//    titleLab.text = self.titleArr[section];
//    [headView addSubview:titleLab];
//    
//    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(headView).offset(15);
//        make.bottom.mas_offset(-10);
//     }];
    
   return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0)return 0.0;
    if(section == 1)return 5;
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        RHPlantInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHPlantInfoCell"];
        cell.model = self.detailModel;
        cell.imgUrl = self.plantModel.imageUrl;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if(indexPath.section == 1){
        //拓扑图
        RHPlantTopoCell *topoCell;
        if(self.plantModel.productTypeId == ProductType_HE_BAT||self.plantModel.productTypeId == ProductType_HE_ALLINONE){
            topoCell = [tableView dequeueReusableCellWithIdentifier:PETopoHEBatCell];
        }
        if(self.plantModel.productTypeId == ProductType_ME){
            topoCell = [tableView dequeueReusableCellWithIdentifier:PETopoMECell];
        }
        if (topoCell == nil) {
            return [UITableViewCell new];
        }
       
        [topoCell setTopoModel:self.detailModel deviceTypeCode:self.plantModel.deviceTypeCode];
        kWeakSelf;
        //全屏
        topoCell.fullScreenAction = ^{
            RHPlantInfoTopoFullScreenVC *fullVC = [[RHPlantInfoTopoFullScreenVC alloc]init];
            fullVC.plantModel = weakSelf.plantModel;
            [weakSelf.navigationController pushViewController:fullVC animated:NO];
        };
        topoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(topoCell == nil) return [UITableViewCell new];
        return topoCell;
    }else if(indexPath.section == 2){
        kWeakSelf;
        //能量统计
        RHEnergyStatisticsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHEnergyStatisticsCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        DevChartModel *chartModel = [self.chartParamsModel.chartList lastObject];
        [cell setChartModel:chartModel];
        //选择参数
        cell.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index atIndexpath:indexPath];
        };
        
        cell.subTimeBlock = ^{//日期往前
            [weakSelf subTimeAction:indexPath];
        };
        
        cell.addTimeBlock = ^{//日期往后
            [weakSelf addTimeAction:indexPath];
        };
        
        cell.changeTimeBlock = ^{//选择日期
            [weakSelf changeDate:indexPath];
        };
        
        //全屏
        cell.fullChartBlock = ^{
            [weakSelf fullAction:indexPath.section];
        };
        cell.contentView.backgroundColor = CFTabViewBgColor;
        return cell;
    }else if (indexPath.section == 3){
        //我的设备
        RHPlantDeviceCell *cell ;
        if (self.deviceArr.count == 1) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"OneDeviceCell"];
        }else if(self.deviceArr.count > 1){
            cell = [tableView dequeueReusableCellWithIdentifier:@"MoreDeviceCell"];
        }else{
            cell = [tableView dequeueReusableCellWithIdentifier:@"NoDeviceCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        kWeakSelf;
        cell.addDeviceBlock = ^{
            RHDeviceBindVC *bindDeviceVC = [[RHDeviceBindVC alloc]init];
            bindDeviceVC.plantModel = weakSelf.plantModel;
            [weakSelf.navigationController pushViewController:bindDeviceVC animated:YES];
        };
        
        cell.deviceListBlock = ^{
            RHDeviceListViewController *vc = [[RHDeviceListViewController alloc] init];
            vc.plantModel = weakSelf.plantModel;
            if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
                //如果是终端用户,显示添加设备按钮
                vc.showAddBtn = YES;
                //如果是终端用户,才可以解绑设备
                vc.canDelete = YES;
            }else{
                vc.canDelete = NO;
            }
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        
        if(self.deviceArr.count == 1 && [PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
            MGSwipeButton *oneBtn = [MGSwipeButton buttonWithTitle:@"   " icon:[UIImage imageNamed:@"plant_delete"] backgroundColor:CFTabViewBgColor padding:15 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
                QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:NULL];
                QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                        //解绑电站下的设备
                       [weakSelf deleteDeviceFromPlantWithDev:weakSelf.deviceArr[0]];
  
                }];
                QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"确定解绑此设备?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
                [alertController addAction:action1];
                [alertController addAction:action2];
                [alertController showWithAnimated:YES];
                
                return YES;
            }];
            cell.rightButtons = @[oneBtn];
        }
        
        [cell setDevices:self.deviceArr totalCount:self.deviceCount];
        return cell;
    }else{
        //社会贡献
        RHEnergySaveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHEnergySaveCell"];
        cell.contentView.backgroundColor = CFTabViewBgColor;
        cell.dic = self.emissionReductionDic;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}



//M1001RE1001011     DEV1691735407840   DEV1691735407840  DEV1691735407840
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.deviceArr.count == 1 && indexPath.section == 3){
        RHDeviceModel *device = [self.deviceArr firstObject];
        if(device.lastOnlineTime == 0){
            [QMUITips showError:@"请让设备先连接云平台".rh_localized];
            return;
        }
        RHDeviceStatusVC *devStatusVC = [[RHDeviceStatusVC alloc]init];
        devStatusVC.deviceModel = self.deviceArr[0];
        [self.navigationController pushViewController:devStatusVC animated:YES];
    }
}


#pragma mark ----------------- Action --------------------
#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------
//工具选择项
- (void)selectTopTool:(NSInteger)index atIndexpath:(NSIndexPath *)indexpath{
    
    DevChartModel *chartModel ;
    
    chartModel = [self.chartParamsModel.chartList firstObject];
    
    
    if (index == 0) {//Day
        chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.dayParams;
        [self.tableView reloadData];
       
    }else if (index == 1) {//Month
        chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.monthParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 2) {//Year
        chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.yearParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 4) {//Total
        chartModel.timeType = TimeType_Total;
       
    }
    
    [self getEnergyStatisticsWithChartModel:chartModel];

}
#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
 
    chartModel = [self.chartParamsModel.chartList firstObject];
   
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYear;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        
       
        [self getEnergyStatisticsWithChartModel:chartModel];
       
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
#pragma mark ------ 后一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
    
    chartModel = [self.chartParamsModel.chartList firstObject];
  
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%ld",(long)interval];
    
    
   
    [self getEnergyStatisticsWithChartModel:chartModel];
    
}

#pragma mark ------ 前一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
  
    chartModel = [self.chartParamsModel.chartList firstObject];
   
    
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    
    [self getEnergyStatisticsWithChartModel:chartModel];
   
}


#pragma mark ---- 全屏
- (void)fullAction:(NSInteger)index{
    DevChartModel *chartModel ;
   
    chartModel = [self.chartParamsModel.chartList firstObject];
    
    NSInteger type = 2;
    if (chartModel.monthParams.count>0) {
        type = 1;
    }
    if (chartModel.yearParams.count>0) {
        type = 0;
    }
    DevChartModel *fullModel = [chartModel modelCopy];
    fullModel.isAllowScale = YES;
    RHEnergyStatisticsFullChartVC *vc = [[RHEnergyStatisticsFullChartVC alloc] initWithModel:fullModel plantModel:self.plantModel toolType:type];
    [self.navigationController pushViewController:vc animated:NO];
   
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
